<template>
    <div class="chooseBox">
        <div class="topTit">
            <span class="left" @click="$emit('close')">取消</span>
            时间选择
            <span class="right" :class="{'disabled' : !visitBeginDate || !visitEndDate || !visitBeginTime || !visitEndTime}" @click="hadleSure()">确定</span>
        </div>
        <van-form ref="form">
            <van-field readonly clickable is-link :label="title + '日期'" :value="showDate" :placeholder="'请选择' + title + '日期范围'" @click="showDatePicker = true" />
            <van-field readonly clickable is-link label="开始时间" :value="visitBeginTime" placeholder="请选择开始时间" @click="showStartTimePicker = true" />
            <van-field readonly clickable is-link label="离开时间" :value="visitEndTime" placeholder="请选择离开时间" @click="showEndTimePicker = true" />
        </van-form>
        <ul v-if="centerConfig.advanceReservationDay || centerConfig.continuousReservationMaxday">
            <li class="title">备注</li>
            <li>可提前预约天数：{{centerConfig.advanceReservationDay || '-'}} 天</li>
            <li>连续预约最大天数：{{centerConfig.continuousReservationMaxday || '-'}} 天</li>
            <li>预约时间：{{centerConfig.beginTime}} ~ {{centerConfig.endTime}}</li>
        </ul>
        <!-- 日期选择 -->
        <van-calendar v-model="showDatePicker" type="range" :allow-same-day="true" :formatter="formatter" @confirm="onDateConfirm" />
        <!-- 时间选择 -->
        <van-popup v-model="showStartTimePicker" position="bottom">
            <van-datetime-picker v-model="pickerTime" :filter="filterStartTime" type="time" title="请选择开始时间" @confirm="onTimeStartConfirm" />
        </van-popup>
        <van-popup v-model="showEndTimePicker" position="bottom">
            <van-datetime-picker v-model="pickerTime" :filter="filterEndTime" type="time" title="请选择离开时间" @confirm="onTimeEndConfirm" />
        </van-popup>
    </div>
</template>

<script>
    export default {
        props: {
            title: {
                type: String,
                default: ''
            }
        },
        data () {
            return {
                showDatePicker: false,
                showStartTimePicker: false,
                showEndTimePicker: false,
                pickerTime: '',
                centerConfig: {
                    advanceReservationDay: '', // 可提前预约天数
                    continuousReservationMaxday: '', // 连续预约最大天数
                    beginTime: '', // 起始时间
                    endTime: '', // 截止时间
                    week: ''
                },
                showDate: '',
                visitBeginDate: '',
                visitEndDate: '',
                visitBeginTime: '',
                visitEndTime: '',
                showDateArr: [],
                releaseDayArr: []
            }
        },
        methods: {
            // 获取访客中心配置信息
            getCenterConfig (data, flag) {
                for (var key in this.centerConfig) {
                    this.centerConfig[key] = data[key];
                }
                if (!flag) {
                    this.pickerTime = data.beginTime;
                    this.showDate = '';
                    this.visitBeginDate = '';
                    this.visitEndDate = '';
                    this.visitBeginTime = '';
                    this.visitEndTime = '';
                    this.showDateArr = [];
                    this.releaseDayArr = [];
                    if (this.centerConfig.advanceReservationDay && this.centerConfig.week) {
                        this.getShowDate();
                    } else if (this.centerConfig.week) {
                        this.releaseDayArr = this.centerConfig.week.split(',');
                    }
                }
            },
            // 根据可提前预约天数和可预约的星期数，获得可选的日期数组
            getShowDate () {
                let days = this.centerConfig.advanceReservationDay;
                let today = Date.now();
                let i = 0;
                let weekArr = this.centerConfig.week.split(',');
                while (this.showDateArr.length < days) {
                    let time = today + 86400000 * i;
                    if (weekArr.indexOf((new Date(time).getDay() || 7) + '') !== -1) {
                        let day = new Date(time).format('yyyy-MM-dd');
                        this.showDateArr.push(day);
                    }
                    i++;
                    continue;
                }
            },
            // 过滤日期
            formatter (day) {
                const _date = day.date.format('yyyy-MM-dd');
                if (this.showDateArr.length && this.showDateArr.indexOf(_date) === -1) {
                    day.type = 'disabled';
                } else if (this.releaseDayArr.length) {
                    let _day = day.date.getDay();
                    if (this.releaseDayArr.indexOf((_day || 7) + '') === -1) {
                        day.type = 'disabled';
                    }
                }
                return day;
            },
            // 时间选择过滤
            filterStartTime (type, options) {
                let beginTime = this.centerConfig.beginTime;
                let endTime = this.centerConfig.endTime;
                if (type === 'hour' && (beginTime || endTime)) {
                    if (beginTime && !endTime) {
                        return options.filter((option) => (option >= beginTime.split(":")[0]));
                    } else if (!beginTime && endTime) {
                        return options.filter((option) => (option >= option <= endTime.split(":")[0]));
                    } else {
                        return options.filter((option) => (option >= beginTime.split(":")[0] && option <= endTime.split(":")[0]));
                    }
                }
                return options;
            },
            filterEndTime (type, options) {
                let beginTime = this.centerConfig.beginTime;
                let endTime = this.centerConfig.endTime;
                if (type === 'hour' && (beginTime || endTime)) {
                    if (beginTime && !endTime) {
                        return options.filter((option) => (option >= beginTime.split(":")[0]));
                    } else if (!beginTime && endTime) {
                        return options.filter((option) => (option >= option <= endTime.split(":")[0]));
                    } else {
                        return options.filter((option) => (option >= beginTime.split(":")[0] && option <= endTime.split(":")[0]));
                    }
                }
                return options;
            },
            // 选中日期范围
            onDateConfirm (date) {
                const [start, end] = date;
                this.visitBeginDate = new Date(start).format('yyyy-MM-dd');
                this.visitEndDate = new Date(end).format('yyyy-MM-dd');
                let maxday = this.centerConfig.continuousReservationMaxday;
                if (this.showDateArr.length) {
                    if ((this.showDateArr.indexOf(this.visitEndDate) - this.showDateArr.indexOf(this.visitBeginDate)) >= maxday) {
                        this.$Notify({ type: 'warning', message: `可连续预约天数不能超过${maxday}天` });
                        return
                    }
                } else if (maxday) {
                    if (((end.getTime() - start.getTime()) / 86400000) > maxday) {
                        this.$Notify({ type: 'warning', message: `可连续预约天数不能超过${maxday}天` });
                        return
                    }
                }
                this.showDate = `${this.visitBeginDate} ~ ${this.visitEndDate}`;
                this.showDatePicker = false;
            },
            // 选择开始时间
            onTimeStartConfirm (time) {
                this.visitBeginTime = time + ':00';
                this.showStartTimePicker = false;
            },
            // 选择离开时间
            onTimeEndConfirm (time) {
                this.visitEndTime = time + ':59';
                this.showEndTimePicker = false;
            },
            hadleSure () {
                if (!this.visitBeginDate || !this.visitEndDate || !this.visitBeginTime || !this.visitEndTime) {
                    return
                }
                if (this.visitBeginTime > this.visitEndTime) {
                    this.$Notify({ type: 'warning', message: '离开时间需要大于开始时间！' });
                    return
                }
                let visitTimeDateStr = [];
                if (this.showDateArr.length) {
                    let ind = this.showDateArr.indexOf(this.visitBeginDate);
                    for (var i = ind; i < this.showDateArr.length; i++) {
                        if (this.showDateArr[i] !== this.visitEndDate) {
                            visitTimeDateStr.push(this.showDateArr[i]);
                        } else {
                            visitTimeDateStr.push(this.showDateArr[i]);
                            break;
                        }
                    }
                } else {
                    visitTimeDateStr.push(this.visitBeginDate);
                    let _time = new Date(this.visitBeginDate).getTime();
                    let _maxTime = new Date(this.visitEndDate).getTime();
                    while (_time < _maxTime) {
                        _time += 86400000;
                        if (this.releaseDayArr.length) {
                            let _day = new Date(_time).getDay();
                            if (this.releaseDayArr.indexOf((_day || 7) + '') !== -1) {
                                visitTimeDateStr.push(new Date(_time).format('yyyy-MM-dd'));
                            }
                        } else {
                            visitTimeDateStr.push(new Date(_time).format('yyyy-MM-dd'));
                        }
                    }
                }
                let params = {
                    visitTime: this.visitBeginDate + " " + this.visitBeginTime,
                    departureTime: this.visitEndDate + " " + this.visitEndTime,
                    visitTimeDateStr: visitTimeDateStr.join(",")
                }
                if (Date.now() > new Date(params.departureTime).getTime()) {
                    this.$Notify({ type: 'warning', message: '所选时间段已过时，请重新选择！' });
                    return
                }
                this.$emit('close');
                this.$emit('sendTime', params);
            }
        }
    }
</script>

<style scoped lang="less">
    .chooseBox {
        background: #fff;
        height: 100%;
        .topTit {
            text-align: center;
            font-size: 16px;
            line-height: 50px;
            border-bottom: 1px solid #eee;
            position: relative;
            & > span {
                position: absolute;
                top: 0;
                font-size: 13px;
            }
            .right {
                right: 17px;
            }
            .left {
                left: 17px;
            }
            .disabled {
                color: #ccc;
            }
        }
        ul {
            color: #999;
            border-top: 1px solid #eee;
            line-height: 25px;
            padding: 10px 17px;
            font-size: 13px;
            .title {
                color: #666;
            }
        }
    }
</style>
